package route

import (
	"fmt"
	"net/http"
	"strings"
)

//Golang学习笔记 - 标准库'net/http'的简析及自制简单路由框架
//http://targetliu.com/2016/8/18/golang-http-router.html

//返回一个Router实例
func NewRouter() *Router {
	return new(Router)
}

//路由结构体，包含一个记录方法、路径的map
type Router struct {
	Route map[string]map[string]http.HandlerFunc
}

//实现Handler接口，匹配方法以及路径
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	fmt.Println("ServeHTTP启动了")
	if h, ok := r.Route[req.Method][req.URL.String()]; ok { //核心代码map[req.Method]map[req.URL.String()]http.HandlerFunc
		fmt.Println("ok:", ok)
		fmt.Println("h的数据:", &h)
		h.ServeHTTP(w, req) //等同于h(w, req)  //调用对应的GetHello方法r.HandleFunc("GET", "/", GetHello)
		return
	}
}

//根据方法、路径将方法注册到路由
func (r *Router) HandleFunc(method, path string, f http.HandlerFunc) {
	fmt.Println("HandleFunc启动了")
	method = strings.ToUpper(method)

	if r.Route == nil {
		r.Route = make(map[string]map[string]http.HandlerFunc)
		fmt.Println("r.Route输出了", r.Route)
	}

	if r.Route[method] == nil {
		r.Route[method] = make(map[string]http.HandlerFunc)
		fmt.Println("r.Route[method]输出了", r.Route[method])
	}
	fmt.Println("f输出了", &f)
	r.Route[method][path] = f //将路由赋值给r.Route
}
